package com.servlet.web;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.Map;
/**
 * @Title: RequestServlet02
 * @Description:
 * @Auther: py
 * @Version: 1.0
 * @create 2023/12/21 14:33
 * 参数信息： 重点
 *   get:携带在url上的参数  key=value&key2=value2。。。。
 *   post:携带在实体内容上的
 *          application/x-www-form-urlencoded   key=value&key2=value2
 *          application/json    "{}"  实体内容 body  通过流的方式获取
 *   get/post 将参数携带在请求头上
 *      headers 上
 */
@WebServlet("/req02")
public class RequestServlet02 extends HttpServlet {

    /**
     * 参数的接收 post的content-type  application/x-www-form-urlencoded
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        // 获取参数信息
        // 1.  获取指定的参数信息  参数都是以字符串的形式传递的
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        System.out.println(username);
        System.out.println(password);
        System.out.println("====================================");
        // 2 获取所有的参数信息  封装成一个map
        Map<String, String[]> parameterMap = req.getParameterMap();
        parameterMap.forEach((key,value) -> {
            System.out.println(key+"\t"+ Arrays.toString(value));
        });
        System.out.println("====================================");
        // 2 获取所有的参数信息  封装成一个枚举
        Enumeration<String> parameterNames = req.getParameterNames();
        while ( parameterNames.hasMoreElements()) {
            String key = parameterNames.nextElement();
            String value = req.getParameter(key);
            System.out.println(key+"\t"+value);
        }
        resp.getWriter().write("success!");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
